package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.VehicleCategory;
import utils.Utils;

public class ListProgramForm extends javax.swing.JFrame {

    public ListProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        programQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Program p");
        programsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programQuery.getResultList());
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(stationQuery.getResultList());
        vehicleCategoryQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select vc from VehicleCategory vc");
        vehicleCategoryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(vehicleCategoryQuery.getResultList());
        programsScrollPanel = new javax.swing.JScrollPane();
        programsTable = new javax.swing.JTable();
        programsLabel = new javax.swing.JLabel();
        newProgramButton = new javax.swing.JButton();
        deleteProgramButton = new javax.swing.JButton();
        editProgramButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Διαχείριση Προγραμμάτων");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programsList, programsTable, "programsList");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Name");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        programsScrollPanel.setViewportView(programsTable);

        programsLabel.setText("Προγράμματα");

        newProgramButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newProgramButton.setText("Νέος");
        newProgramButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newProgramButtonActionPerformed(evt);
            }
        });

        deleteProgramButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteProgramButton.setText("Διαγραφή");
        deleteProgramButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteProgramButtonActionPerformed(evt);
            }
        });

        editProgramButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editProgramButton.setText("Επεξεργασία");
        editProgramButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editProgramButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(newProgramButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteProgramButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editProgramButton)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(programsScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 836, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cancelButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(saveButton))
                                    .addComponent(programsLabel))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(programsLabel)
                .addGap(18, 18, 18)
                .addComponent(programsScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newProgramButton)
                    .addComponent(deleteProgramButton)
                    .addComponent(editProgramButton))
                .addGap(99, 99, 99)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newProgramButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProgramButtonActionPerformed

       p = new Program();
       em.persist(p);
       List<ProgramRate> prl = p.getProgramRateList();
       if (prl==null){
           prl = new ArrayList<ProgramRate>();
           p.setProgramRateList(prl);
       }
       for (Station s: stationList){
           for (VehicleCategory vc: vehicleCategoryList){
               ProgramRate pr = new ProgramRate();
               pr.setCategoryId(vc);
               pr.setStationId(s);
               pr.setProgramId(p);
               em.persist(pr);
               p.getProgramRateList().add(pr);
               // Παραδοχή - default rate: 2 ευρώ
               pr.setRate(new BigDecimal(2.00));
           }
       }
       // Παραδοχή - default pay limit: 20
       p.setPayLimit(20);
      
       EditProgramForm epf = new EditProgramForm(p,false);
       
       epf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    programsList.add(p);
                    int row = programsList.size() - 1;
        
                    programsTable.setRowSelectionInterval(row, row);
                    programsTable.scrollRectToVisible(programsTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    for (ProgramRate pr : p.getProgramRateList()) { 
                         em.remove(pr);
                    }
                    em.remove(p);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
       

    }//GEN-LAST:event_newProgramButtonActionPerformed

    private void deleteProgramButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteProgramButtonActionPerformed
        
        int s = programsTable.getSelectedRow();
        if (s>=0) {
            Program p = programsList.get(programsTable.convertRowIndexToModel(s));
            // Έλεγχος για το αν το πρόγραμμα μπορεί να διαγραφεί
            if (p.getCardList().size() == 0) { 
                // Επιβεβαίωση της διαγραφής
                int choice = JOptionPane.showConfirmDialog(this,
                                          "Διαγραφή του συγκεκριμένου προγράμματος;",
                                          "Επιβεβαίωση διαγραφής οχήματος",
                                          JOptionPane.YES_NO_OPTION);
                
                if (choice != 0)
                    return;
                
                programsList.remove(p);
                for (ProgramRate pr : p.getProgramRateList()) { 
                     em.remove(pr);
                }
                em.remove(p);
                utils.Utils.updateJTable(programsTable, bindingGroup, "programsList");
                
            } else { 
                JOptionPane.showMessageDialog(this, "Το πρόγραμμα δεν μπορεί να διαγραφεί (έχει ανατεθεί σε κάρτες).",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_deleteProgramButtonActionPerformed

    private void editProgramButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editProgramButtonActionPerformed

       s = programsTable.getSelectedRow();
       
       if (s >= 0) {
           p = programsList.get(s);
           EditProgramForm ecf = new EditProgramForm(p,true);
       
           ecf.setVisible(true);
           thisFrame=this;
           thisFrame.setEnabled(false);
        //************
        ecf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave){
                    
                    programsList.set(s,p);
                    programsTable.setRowSelectionInterval(s, s);
                    programsTable.scrollRectToVisible(programsTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    for (ProgramRate pr : p.getProgramRateList()) { 
                         em.refresh(pr);
                    }
                    em.refresh(p);
                    Utils.updateJTable(programsTable, bindingGroup, "programsList");
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
       }
    }//GEN-LAST:event_editProgramButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteProgramButton;
    private javax.swing.JButton editProgramButton;
    private javax.swing.JButton newProgramButton;
    private javax.persistence.Query programQuery;
    private javax.swing.JLabel programsLabel;
    private java.util.List<Program> programsList;
    private javax.swing.JScrollPane programsScrollPanel;
    private javax.swing.JTable programsTable;
    private javax.swing.JButton saveButton;
    private java.util.List<Station> stationList;
    private javax.persistence.Query stationQuery;
    private java.util.List<VehicleCategory> vehicleCategoryList;
    private javax.persistence.Query vehicleCategoryQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    JFrame thisFrame;
    Program p;
    int s ;
}
